package com.asa.ui.G;

import java.awt.EventQueue;

import com.asa.ui.G.AlgoFrame;
import com.asa.ui.frame.AlgoVisHelper;

public class AlgoVisualizer {

	private AlgoFrame frame;
	private MazeData data;
	private int screenWidth;
	private int screenHeight;

	public AlgoVisualizer(String fileName) {
		data = new MazeData(fileName);
		this.screenWidth = data.getMazeL() * Constant.BLOCK;
		this.screenHeight = data.getMazeW() * Constant.BLOCK;
		// 初始化视图
//	EventQueue.invokeLater(()->{
//		frame=new AlgoFrame("maze",screenWidth,screenHeight);
//		new Thread(()->run()).start();
//	});

		//注释调这个就不会画图了
		EventQueue.invokeLater(new Runnable() {// 用java事件分发（开了个线程）的方法来创建对话框

			@Override
			public void run() {
				// TODO Auto-generated method stub
				frame = new AlgoFrame("maze", screenWidth, screenHeight);

				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						runmiage();
						
					}

				}).start();
				;

			}
		});

	}
	
	
	public AlgoVisualizer(String[][] basedata) {
		data = new MazeData(basedata);
		this.screenWidth = data.getMazeL() * Constant.BLOCK;
		this.screenHeight = data.getMazeW() * Constant.BLOCK;
		// 初始化视图
//	EventQueue.invokeLater(()->{
//		frame=new AlgoFrame("maze",screenWidth,screenHeight);
//		new Thread(()->run()).start();
//	});

		//注释调这个就不会画图了
		EventQueue.invokeLater(new Runnable() {// 用java事件分发（开了个线程）的方法来创建对话框

			@Override
			public void run() {
				// TODO Auto-generated method stub
				frame = new AlgoFrame("maze", screenWidth, screenHeight);

				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						runmiage();
						
					}

				}).start();
				;

			}
		});

	}
	
	
	

//播放动画
	public void runmiage() {
		setData(-1, -1, false);
		go(1, 0);
		setData(-1, -1, false);
	}

	//设置某个点是否是路径
	private void setData(int x, int y, boolean isPath) {
		data.setExitX(data.getMazeL() - 2);
		data.setExitY(data.getMazeW() - 1);
		if (!data.isIllegal(x, y)) {
			data.path[x][y] = isPath;
		}
		frame.render(data);
		AlgoVisHelper.pause(0);
	}

//走迷宫
	public boolean go(int x, int y) {
		if (data.isIllegal(x, y)) {
			throw new IllegalArgumentException("数组越界");
		}
		setData(x, y, true);
		// 标记访问
		data.visited[x][y] = true;
		// 如果是出口返回true
		if (data.getExitX() == x && data.getExitY() == y) {
			return true;
		}
		for (int i = 0; i < 4; i++) {
			int newX = data.distance[i][0] + x;
			int newY = data.distance[i][1] + y;
			if (!data.isIllegal(newX, newY) && data.getMazeElement(newX, newY) == Constant.ROAD
					&& !data.visited[newX][newY]) {
				if (go(newX, newY)) {
					return true;
				}
			}
		}
		setData(x, y, false);
		return false;
	}

	public static void main(String[] args) {
//		new AlgoVisualizer("maze_101_101.txt");
		new AlgoVisualizer(MapCreate.map2d());

	}
}
